﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Edge.Business.Domain.Application;
using Edge.Common;
using Edge.Common.ComponentModel.Parameters;
using Edge.Common.Services;
using Edge.Common.Utils;
using Shop.Business.Domain.Catalog;
using Shop.Business.Domain.Customers;
using Shop.Business.Domain.Pricing;
using Shop.Web.AppCode;
using Action = Edge.Common.Web.Navigation.Action;

namespace Shop.Web
{
    public partial class ProductDetails : ShopBasePage
    {
        [QueryParameter("action", IsRequired = false)]
        public Action action = Action.New;

        [QueryParameter("id", IsRequired = false)]
        public int id;

        protected void Page_Load(object sender, EventArgs e)
        {
            WebParameterAttribute.SetValues(this, Request);
            HandlePage();
            if (!IsPostBack)
            {
                if (id > 0 && action == Action.New)
                    action = Action.View;
                switch (action)
                {
                    case Action.View:
                        tbName.IsLabel = true;
                        tbDescription.IsLabel = true;
                        ddlBrand.IsLabel = true;
                        ddlStatus.IsLabel = true;
                        lblCategory.Visible = true;
                        phCategory.Visible = false;
                        btnEdit.Visible = true;
                        btnDelete.Visible = true;
                        fuImage.Visible = false;
                        fuImage1.Visible = false;
                        fuImage2.Visible = false;
                        fuImage3.Visible = false;
                        fuImage4.Visible = false;
                        break;
                    case Action.New:
                        tbName.IsLabel = false;
                        tbDescription.IsLabel = false;
                        btnSave.Visible = true;
                        btnCancel.Visible = true;
                        break;
                    case Action.Edit:
                        btnSave.Visible = true;
                        btnCancel.Visible = true;
                        btnDelete.Visible = true;
                        btnUnMerge.Visible = true;
                        break;
                    default:
                        break;

                }
                DataBind();
            }
        }

        private void SetupImage(ProductGroup group, HtmlImage img)
        {
            SetupImage(group, img, false,0);
        }

        private void SetupImage(ProductGroup group, HtmlImage img, bool subImage, int position)
        {
            string path = HttpContext.Current.Server.MapPath("images") + "\\Product\\";
            string fileName = string.Format("thumb_IMG{0}.jpg", group.Id);
            if (subImage)
            {
                path += "\\F"+group.Id+"\\";
                fileName = string.Format("thumb_IMG{0}_"+position.ToString()+".jpg", group.Id);
            }
            if (
                   File.Exists(path +
                               fileName))
            {
                img.Attributes["src"] = subImage == false ? "~/images/Product/" + fileName : "~/images/Product/F" +group.Id+"/"+ fileName;
                if (
                    File.Exists(path +
                                fileName.Replace("thumb_","")))
                {
                    img.Attributes["class"] = "wrap ui-corner-all";
                    img.Attributes["longdesc"] = subImage == false ? "~/images/Product/" + fileName.Replace("thumb_", "") : "~/images/Product/F" + group.Id + "/" + fileName.Replace("thumb_", "");
                }
            }
            else
            {
                img.Attributes["src"] = ShopBasePage.NoImage;
                img.Attributes["class"] = "ui-corner-all";
            }
        }

        protected void DataBind()
        {
            ddlBrand.DataSource = Locator.GetService<IBrandManager>().FindAll();
            ddlBrand.DataTextField = "Name";
            ddlBrand.DataValueField = "Id";
            ddlBrand.DataBind();
            ddlStatus.DataSource = EnumUtils.GetEnumDataSource<GroupStatus>();
            ddlStatus.DataValueField = "Value";
            ddlStatus.DataTextField = "Key";
            ddlStatus.DataBind();
            ddlStatus.Items.Insert(0, new ListItem("", ""));
            ddlStatus.SelectedValue = "";
            ddlCat.DataSource = Locator.GetService<ICategoryManager>().FindAll();
            ddlCat.DataTextField = "Name";
            ddlCat.DataValueField = "Id";
            ddlCat.DataBind();

            ProductGroup group = null;
            if (id > 0)
                group = Locator.GetService<IProductGroupManager>().Load(id);
            if (group != null)
            {
                hlHeader.Text = group.Name;
                hlHeader.NavigateUrl = "Product.aspx?id=" + group.Id.ToString();
                tbName.Text = group.Name;
                tbDescription.Text = group.Description;
                ddlBrand.SelectedValue = group.Brand.Id.ToString();
                ddlCat.SelectedValue = group.Category.Id.ToString();
                SetupImage(group,imgProduct);
                SetupImage(group,img1,true,1);
                SetupImage(group,img2,true,2);
                SetupImage(group,img3,true,3);
                SetupImage(group,img4,true,4);
                if (group.Status != null)
                {
                    ddlStatus.SelectedValue = group.Status.Value.ToString();
                }
                chbVisible.Checked = group.Visible;
                ProductFilter filter  = new ProductFilter();
                filter.Group = group;
                List<Product> list = Locator.GetService<IProductManager>().Find(FetchOptions.All,filter).ToList();
                Dictionary<string, List<Product>> dictionary = new Dictionary<string, List<Product>>();
                foreach (Product product in list)
                {
                    if (!dictionary.Keys.Contains(product.BrandArt))
                        dictionary.Add(product.BrandArt, new List<Product>());
                    dictionary[product.BrandArt].Add(product);
                }
                rprBrandArt.DataSource = dictionary;
                rprBrandArt.DataBind();
                rprProduct.DataSource = list.OrderBy(p => p.BrandArt);
                rprProduct.DataBind();
            }


        }
        public class AbstractComparer : IEqualityComparer<Product>
        {
            public bool Equals(Product x, Product y)
            {
                return x.BrandArt == y.BrandArt;
            }

            public int GetHashCode(Product obj)
            {
                return obj.BrandArt.GetHashCode();
            }
        }

        protected void HandlePage()
        {
            if (Locator.GetService<IContextObjects>().Get<CustomerHolder>() == null)
                AccessDeniedMessage();
            else
            {
                Customer cc = Locator.GetService<IContextObjects>().Get<CustomerHolder>().Object;
                switch (cc.Role)
                {
                    case CustomerRole.Buyer:
                        action = Action.View;
                        if (id <= 0)
                            AccessDeniedMessage();
                        break;
                    case CustomerRole.Manager:
                        btnDelete.Visible = false;
                        break;
                    case CustomerRole.Admin:
                        break;
                    default:
                        break;

                }
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            ProductGroup group = new ProductGroup();
            if (id > 0)
                group = Locator.GetService<IProductGroupManager>().Load(id);
            group.Name = tbName.Text;
            group.Description = tbDescription.Text;
            group.Category = Locator.GetService<ICategoryManager>().Load(Convert.ToInt32(ddlCat.SelectedValue));
            group.Brand = Locator.GetService<IBrandManager>().Load(Convert.ToInt32(ddlBrand.SelectedValue));
            if (!StringUtils.IsEmptyOrNull(ddlStatus.SelectedValue))
                group.Status = (GroupStatus)Enum.Parse(typeof(GroupStatus), ddlStatus.SelectedValue);
            group.Visible = chbVisible.Checked;
            Locator.GetService<IProductGroupManager>().Update(group);
            if (fuImage.PostedFile != null)
            {
                FileUtils.UploadImg(fuImage.PostedFile, HttpContext.Current.Server.MapPath("images") + "\\" + "Product/", string.Format("IMG{0}.jpg", group.Id), HttpContext.Current.Server.MapPath("images") + "\\" + "Default\\watermark.gif");
            }
            if (fuImage1.PostedFile != null)
            {
                FileUtils.UploadImg(fuImage1.PostedFile, HttpContext.Current.Server.MapPath("images") + "\\" + "Product/F" + group.Id +"/", string.Format("IMG{0}_1.jpg", group.Id), HttpContext.Current.Server.MapPath("images") + "\\" + "Default\\watermark.gif");
            } 
            if (fuImage2.PostedFile != null)
            {
                FileUtils.UploadImg(fuImage2.PostedFile, HttpContext.Current.Server.MapPath("images") + "\\" + "Product/F" + group.Id + "/", string.Format("IMG{0}_2.jpg", group.Id), HttpContext.Current.Server.MapPath("images") + "\\" + "Default\\watermark.gif");
            }
            if (fuImage3.PostedFile != null)
            {
                FileUtils.UploadImg(fuImage3.PostedFile, HttpContext.Current.Server.MapPath("images") + "\\" + "Product/F" + group.Id + "/", string.Format("IMG{0}_2.jpg", group.Id), HttpContext.Current.Server.MapPath("images") + "\\" + "Default\\watermark.gif");
            }
            if (fuImage4.PostedFile != null)
            {
                FileUtils.UploadImg(fuImage4.PostedFile, HttpContext.Current.Server.MapPath("images") + "\\" + "Product/F" + group.Id + "/", string.Format("IMG{0}_2.jpg", group.Id), HttpContext.Current.Server.MapPath("images") + "\\" + "Default\\watermark.gif");
            }
            DataBind();
            //Response.Redirect("ProductDetaaspx?id=" + group.Id.ToString());
        }

        protected void btnEdit_Click(object sender, EventArgs e)
        {
            Response.Redirect("ProductDetails.aspx?action=edit&id=" + id.ToString());
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect("Catalog.aspx");
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            ProductGroup group = null;
            if (id > 0)
                group = Locator.GetService<IProductGroupManager>().Load(id);
            if (group != null)
            {
                Locator.GetService<IProductGroupManager>().Delete(group);
            }
            Response.Redirect("Catalog.aspx");
        }

        protected void btnUnMerge_Click(object sender, EventArgs e)
        {
            List<string> list = new List<string>();
            foreach (RepeaterItem repeaterItem in rprBrandArt.Items)
            {
                CheckBox chbUnMerge = (CheckBox) repeaterItem.FindControl("chbUnMerge");
                if (chbUnMerge != null && chbUnMerge.Checked)
                {
                    list.Add(chbUnMerge.Text);
                }
            }
            if (list.Count > 0)
            {
                ProductGroup newProductGroup = new ProductGroup();
                ProductGroup group = Locator.GetService<IProductGroupManager>().Load(id);
                newProductGroup.Name = group.Name;
                newProductGroup.Brand = group.Brand;
                newProductGroup.Category = group.Category;
                newProductGroup.Description = group.Description;
                newProductGroup.Status = group.Status;
                newProductGroup.Visible = group.Visible;
                Locator.GetService<IProductGroupManager>().Save(newProductGroup);
                foreach (string s in list)
                {
                    Locator.GetService<IProductManager>().ChangeGroupForBrandArt(s,newProductGroup);
                }
                Response.Redirect("ProductDetails.aspx?action=edit&id="+newProductGroup.Id.ToString());
            }

        }

        protected void btnUpdateProductList_Click(object sender, EventArgs e)
        {
            foreach (RepeaterItem item in rprProduct.Items)
            {
                HiddenField hdnProductId = (HiddenField) item.FindControl("hdnProductId");
                if (hdnProductId != null)
                {
                    Product product = Locator.GetService<IProductManager>().Load(Convert.ToInt32(hdnProductId.Value));
                    if (product != null)
                    {
                        CheckBox chbVisible = (CheckBox) item.FindControl("chbVisible");
                        if (chbVisible != null)
                        {
                            product.Visible = chbVisible.Checked;
                        }
                        TextBox tbQty = (TextBox) item.FindControl("tbQty");
                        if (tbQty != null)
                        {
                            product.PriceItem.Qty = Convert.ToInt32(tbQty.Text);
                            product.Qty = Convert.ToInt32(tbQty.Text);
                        }
                        TextBox tbPrice = (TextBox) item.FindControl("tbPrice");
                        TextBox tbWhlPrice = (TextBox)item.FindControl("tbWhlPrice");
                        if (tbPrice != null && tbWhlPrice!= null)
                        {
                            Decimal newPrice = Convert.ToDecimal(tbPrice.Text);
                            Decimal newWhlPrice = Convert.ToDecimal(tbWhlPrice.Text);
                            if (newPrice != product.PriceItem.Price || product.PriceItem.WholesellPrice != newWhlPrice)
                            if (product.PriceItem.Qty > 0)
                            {
                                product.PriceItem.Price = newPrice;
                                product.Price = newPrice;
                                product.PriceItem.WholesellPrice = newWhlPrice;
                            }
                            else 
                            {
                                PriceItem priceItem = new PriceItem();
                                priceItem.Product = product;
                                priceItem.CreatedBy = Locator.GetService<IContextObjects>().Get<CustomerHolder>().Object;
                                priceItem.Price = newPrice;
                                priceItem.WholesellPrice = newWhlPrice;
                                priceItem.Qty = product.PriceItem.Qty;
                                product.Price = newPrice;
                            }
                        }
                        
                        Locator.GetService<IProductManager>().Save(product);
                    }
                }
            }
            DataBind();
        }
    }
}
